import hashlib
import os.path
from flask import Blueprint, request, render_template, redirect, url_for, jsonify, session, g
from flask_restful import Api, Resource, reqparse, inputs, fields, marshal, marshal_with
from sqlalchemy import or_
from werkzeug.security import generate_password_hash, check_password_hash
from datamp.user.models import *
from datamp.app.models import MarketSubjectType
from ext import db
from werkzeug.utils import secure_filename
from werkzeug.datastructures import FileStorage
from settings import Config

app_bp = Blueprint('app', __name__, url_prefix='/app', template_folder='templates')

api = Api(app_bp)
required_login_list = ['/app/manage', '/app/monitor']

manage_register_parser = reqparse.RequestParser()
manage_register_parser.add_argument('app_name', type=str, help='应用名字不对', required=True,
                                    location=['form', 'args', 'json'])
manage_register_parser.add_argument('company_name', type=str, help='厂商名字不对', required=True,
                                    location=['form', 'args', 'json'])
manage_register_parser.add_argument('app_target_user', type=str, help='应用对象不对', required=False,
                                    location=['form', 'args', 'json'])
manage_register_parser.add_argument('category_id', type=str, help='应用对象不对', required=False,
                                    location=['form', 'args', 'json'])



# 钩子函数
@app_bp.before_app_first_request
def first_request():
    print('before_app_first_request')


# 钩子函数
@app_bp.before_app_request
def before_request1():
    print('before_app_request', request.path)
    if request.path in required_login_list:
        id = session.get('uid')
        if not id:
            return render_template('login.html')
        else:
            user = StudentInfo.query.get(id)
            # g对象，本次请求的对象
            g.user = user


# ------第三方应用管理------
# 1. 开放应用管理

@app_bp.route('/app/manage')
def app_manage():
    return render_template("manage.html")


class AppManagerRegister(Resource):
    def post(self):
        args = manage_register_parser.parse_args()
        app_name = args.get('app_name')
        company_name = args.get('company_name')
        category_id = args.get('category_id')
        app_target_user = args.get('app_target_user')
        app_mangers = AppManger.query.filter(AppManger.app_name == app_name).all()
        if app_mangers:
            print(app_mangers)
            for app_manger in app_mangers:
                flag = AppManger.query.filter(AppManger.companyname == company_name).first()
                print(flag)
                if flag:
                    return jsonify({'code': 1, 'msg': '应用已存在，注册失败', 'app_name': app_manger.app_name})
                else:
                    # 与模型结合
                    app_manger = AppManger()
                    app_manger.app_name = app_name
                    app_manger.company_name = company_name
                    app_manger.category_id = category_id
                    app_manger.app_target_user = app_target_user
                    # 添加
                    db.session.add(app_manger)
                    # 提交
                    db.session.commit()
                    # return redirect(url_for('index'))
                    return jsonify({'code': 0, 'msg': '应用注册成功', 'app_name': app_manger.app_name})
        else:
            app_manger = AppManger()
            app_manger.app_name = app_name
            app_manger.company_name = company_name
            app_manger.category_id = category_id
            app_manger.app_target_user = app_target_user
            # 添加
            db.session.add(app_manger)
            # 提交
            db.session.commit()
            # return redirect(url_for('index'))
            return jsonify({'code': 0, 'msg': '应用注册成功', 'app_name': app_manger.app_name})


api.add_resource(AppManagerRegister, '/AppManagerRegister')


class AppManagerShow(Resource):
    # 可以使用装饰器来序列化
    def get(self):
        app_mangers = AppManger.query.filter(AppManger.isdelete == False).all()
        print(type(app_mangers))
        load_app_list = []
        data_app = {}
        for app_manger in app_mangers:
            aa = {'appid': app_manger.id,
                  'app_name': app_manger.app_name,
                  'company_name': app_manger.company_name,
                  'category_id': app_manger.category_id,
                  'app_target_user': app_manger.app_target_user,
                  'date_time': app_manger.date_time
                  }
            data_app.update(aa)
            load_app_list.append(data_app)
            data_app = {}
        return jsonify({'msg': '获取成功',
                        'status': 200,
                        'data': load_app_list
                        })
        # return marshal({'msg': '获取成功', 'status': 200, 'data': persons}, result_fileds)


api.add_resource(AppManagerShow, '/AppManagerShow')


# ### 2.1 注册新应用
# 描述：管理员注册第三方应用
#
# 接口：/app/manage/register
#
# 方法：POST
#
# 参数：
# - 应用名称: app_name
# - 应用URL: app_url
# - 应用对象: app_name
# - 应用类型: app_style
# - 应用平台: app_system
# - 应用图标: app_icon
#
# ![](media/app_info.png)
#
# 返回：
# - code: 0 / 1
# - msg: 注册成功 / 注册失败(应用已存在/其他问题...)
#
# 备注：
# - 返回注册失败时，请在msg的括号中标注问题类型


# 2. 第三方应用监控
@app_bp.route('/app/monitor')
def app_monitor():
    return render_template("monitor.html")
